package com.xzx.controller;

import com.xzx.dto.CommonPage;
import com.xzx.dto.SuccessResponseDTO;
import com.xzx.dto.Tuple2;
import com.xzx.po.PermissionPO;
import com.xzx.po.RolePO;
import com.xzx.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *
 * @author xinzhixuan
 * @version 1.0
 * @date 2025/8/18 14:08
 */
@Slf4j
@RequestMapping("/role")
@Controller
public class RoleController {

    @Autowired
    private RoleService roleService;

    @GetMapping("/list")
    public String list(@RequestParam(name = "query", required = false) String query,
                       @RequestParam(name = "page", required = false, defaultValue = "1") int  page,
                       @RequestParam(name = "size", required = false, defaultValue = "2") int  size,
                       Model model) {
        CommonPage<RolePO> list = roleService.list(query, page, size);
        model.addAttribute("result", list);
        model.addAttribute("query", query);
        return "role/list";
    }

    @ResponseBody
    @PostMapping("/doAdd")
    public String doAdd(@RequestBody RolePO rolePO) {
        roleService.doAdd(rolePO);
        return "ok";
    }

    @ResponseBody
    @PostMapping("/doDelete")
    public SuccessResponseDTO doDelete(@RequestParam("ids") List<Long> ids) {
        roleService.delete(ids);
        return SuccessResponseDTO.of();
    }

    @GetMapping("/edit")
    public String edit(@RequestParam("id") Long id, Model model) {
        RolePO rolePO = roleService.getById(id);
        model.addAttribute("role", rolePO);

        return "role/edit";
    }

    @ResponseBody
    @PostMapping("/doEdit")
    public SuccessResponseDTO doEdit(@RequestBody RolePO rolePO) {
        log.info("doEdit rolePO:{}", rolePO);
        roleService.doEdit(rolePO);
        return SuccessResponseDTO.of();
    }

    @GetMapping("/assignPermission")
    public String assignPermission(@RequestParam("id") Long id, Model model) {
        log.info("assignPermission id:{}", id);
        List<PermissionPO> tree = roleService.selectAllPermission(id);
        model.addAttribute("tree", tree);
        return "role/assignPermission";
    }

    @ResponseBody
    @PostMapping("/doAssign")
    public SuccessResponseDTO doAssign(@RequestParam("roleId") Long roleId,
                                       @RequestParam("permissionIds") List<Long> permissionIds){
        roleService.doAssignPermission(roleId, permissionIds);
        return SuccessResponseDTO.of();
    }

}
